package com.yao.sys.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.common.exception.BusinessException;
import com.yao.sys.entity.AccountEntity;
import com.yao.sys.entity.dto.AccountDto;
import com.yao.sys.entity.dto.UserDto;
import com.yao.sys.mapper.AccountMapper;
import com.yao.sys.service.AccountService;
import com.yao.sys.service.UserService;

import cn.hutool.crypto.SecureUtil;

/**
 * 账户表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-04-09
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountDto> implements AccountService {

    @Autowired
    private UserService userService;

    @Override
    @Transactional(isolation = Isolation.REPEATABLE_READ, rollbackFor = BusinessException.class)
    public void add(AccountDto model) {
        // 根据手机号查重
        if (checkPhone(model.getPhone())) {
            throw new BusinessException("手机号相同.{}", model.getPhone());
        }

        // MD5加密password
        String encryptPwd = SecureUtil.md5(model.getPassword());

        model.setOperator(0);
        model.setPassword(encryptPwd);

        if (!this.save(model)) {
            throw new BusinessException("新增账号失败.");
        }

        UserDto user = new UserDto();
        user.setAccountId(model.getId());
        user.setUserName(model.getName());
        user.setPassword(encryptPwd);
        user.setIdCard(model.getIdCard());
        user.setPhone(model.getPhone());
        user.setSort(1);

        if (!userService.save(user)) {
            throw new BusinessException("新增用户失败.");
        }

    }

    @Override
    public void modifyById(AccountDto model) {
        // 根据手机号查重
        if (checkPhone(model.getPhone())) {
            throw new BusinessException("手机号相同.{}", model.getPhone());
        }

        if (!this.updateById(model)) {
            throw new BusinessException("更新账号失败.");
        }
    }

    @Override
    public IPage<AccountDto> page(Page<AccountDto> page, AccountDto dto) {

        LambdaQueryWrapper<AccountDto> query = Wrappers.lambdaQuery();

        return this.page(page, query);
    }

    private boolean checkPhone(String phone) {
        LambdaQueryWrapper<AccountDto> query = Wrappers.lambdaQuery();
        query.eq(AccountEntity::getPhone, phone);

        return null != this.getOne(query);
    }
}